<template>
	<view class="container">
		<!-- 标题 -->
		<view class="header">
			<text class="title">项目清单</text>
		</view>
		
		<!-- 添加区域 -->
		<view class="add-area">
			<input 
				class="add-input" 
				v-model="newItemName" 
				placeholder="输入项目名称" 
				@keypress.enter="addItem"
			/>
			<button class="add-btn" @click="addItem">添加</button>
		</view>
		
		<!-- 操作区域 -->
		<view class="action-area">
			<button class="action-btn parse-btn" @click="showParseModal">解析项目</button>
			<button class="action-btn reset-btn" @click="resetToDefault">重置默认列表</button>
		</view>
		
		<!-- 项目列表 -->
		<view class="items-list">
			<view 
				v-for="(item, index) in items" 
				:key="index" 
				class="item-card"
				:class="{'dragging': draggingIndex === index}"
				@touchstart="startDrag(index)"
				@touchmove="onDrag"
				@touchend="endDrag"
			>
				<view class="drag-handle">≡</view>
				<checkbox 
					:checked="item.checked" 
					@change="item.checked = !item.checked"
					class="item-checkbox"
				/>
				<text class="item-name">{{item.name}}</text>
				<view class="item-quantity">
					<button class="quantity-btn" @click="decreaseQuantity(index)">-</button>
					<text class="quantity-text">{{item.quantity}}</text>
					<button class="quantity-btn" @click="increaseQuantity(index)">+</button>
				</view>
				<button class="delete-btn" @click="deleteItem(index)">×</button>
			</view>
		</view>
		
		<!-- 添加新项目按钮 -->
		<button class="add-new-btn" @click="addNewItem">添加新项目</button>
		
		<!-- 描述区域 -->
		<view class="description-area">
			<text class="description-title">项目描述：</text>
			<view class="description-content">
				<text v-for="(line, idx) in description" :key="idx" class="description-line">{{line}}</text>
			</view>
			<button class="copy-btn" @click="copyDescription">{{copyStatus}}</button>
		</view>
		
		<!-- 历史记录区域 -->
		<view class="history-area" v-if="history.length > 0">
			<text class="history-title">历史记录：</text>
			<view 
				v-for="(record, index) in history" 
				:key="index" 
				class="history-item"
			>
				<text class="history-date">{{record.date}}</text>
				<text class="history-content">{{record.content}}</text>
				<view class="history-actions">
					<button class="history-btn" @click="copyHistory(index)">复制</button>
					<button class="history-btn" @click="parseHistory(index)">解析</button>
				</view>
			</view>
		</view>
		
		<!-- 解析弹窗 -->
		<view class="modal" v-if="showModal">
			<view class="modal-content">
				<text class="modal-title">解析项目</text>
				<text class="modal-desc">支持多种格式：如"牛奶 2袋"、"2袋 牛奶"、"牛奶 x 2"或仅项目名</text>
				<textarea 
					class="parse-input" 
					v-model="parseText" 
					placeholder="请输入或粘贴项目列表文本"
				/>
				<view class="parse-result" v-if="parseResult.length > 0">
					<text class="result-title">解析结果预览：</text>
					<view 
						v-for="(item, index) in parseResult" 
						:key="index" 
						class="result-item"
					>
						<text>{{item.name}} {{item.quantity}}{{item.unit}}</text>
					</view>
				</view>
				<view class="modal-buttons">
					<button class="modal-btn cancel-btn" @click="cancelParse">取消</button>
					<button class="modal-btn parse-action-btn" @click="parseItems">解析</button>
					<button class="modal-btn confirm-btn" v-if="parseResult.length > 0" @click="confirmParse">确认</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				items: [],
				newItemName: '',
				parseText: '',
				parseResult: [],
				showModal: false,
				copyStatus: '复制描述',
				history: [],
				draggingIndex: -1,
				startY: 0,
				currentY: 0,
				units: ['个', '袋', '盒', '包', '瓶', '罐', '支', '条', '片', '块', '份']
			}
		},
		computed: {
			description() {
				const lines = [];
				this.items.forEach(item => {
					if (item.checked && item.quantity > 0) {
						lines.push(`${item.name} ${item.quantity}${item.unit || '个'}`);
					}
				});
				return lines;
			}
		},
		created() {
			this.loadData();
			// 如果没有数据，初始化默认项目
			if (this.items.length === 0) {
				this.resetToDefault();
			}
		},
		methods: {
			// 项目管理功能
			addItem() {
				if (!this.newItemName.trim()) return;
				
				this.items.push({
					name: this.newItemName,
					quantity: 0,
					checked: true,
					unit: '个'
				});
				
				this.newItemName = '';
				this.saveData();
			},
			addNewItem() {
				this.items.push({
					name: '新项目',
					quantity: 0,
					checked: true,
					unit: '个'
				});
				this.saveData();
			},
			deleteItem(index) {
				this.items.splice(index, 1);
				this.saveData();
			},
			increaseQuantity(index) {
				this.items[index].quantity++;
				this.saveData();
			},
			decreaseQuantity(index) {
				if (this.items[index].quantity > 0) {
					this.items[index].quantity--;
					this.saveData();
				}
			},
			
			// 拖拽排序功能
			startDrag(index) {
				this.draggingIndex = index;
				this.startY = event.touches[0].clientY;
			},
			onDrag(event) {
				if (this.draggingIndex === -1) return;
				
				this.currentY = event.touches[0].clientY;
				const moveY = this.currentY - this.startY;
				
				// 计算潜在的新位置
				const itemHeight = 60; // 假设每个项目的高度约为60px
				const potentialNewIndex = this.draggingIndex + Math.round(moveY / itemHeight);
				
				// 确保新位置在有效范围内
				if (potentialNewIndex >= 0 && potentialNewIndex < this.items.length && 
					potentialNewIndex !== this.draggingIndex) {
					// 交换项目位置
					const temp = this.items[this.draggingIndex];
					this.items.splice(this.draggingIndex, 1);
					this.items.splice(potentialNewIndex, 0, temp);
					
					// 更新拖拽索引
					this.draggingIndex = potentialNewIndex;
					this.startY = this.currentY;
				}
			},
			endDrag() {
				this.draggingIndex = -1;
				this.saveData();
			},
			
			// 批量处理功能
			resetToDefault() {
				this.items = [
					{ name: '百洁布', quantity: 0, checked: true, unit: '个' },
					{ name: '牛奶', quantity: 0, checked: true, unit: '袋' },
					{ name: '泡面', quantity: 0, checked: true, unit: '包' }
				];
				this.saveData();
			},
			
			// 解析功能
			showParseModal() {
				this.showModal = true;
				this.parseText = '';
				this.parseResult = [];
			},
			parseItems() {
				if (!this.parseText.trim()) return;
				
				const lines = this.parseText.split('\n').filter(line => line.trim());
				this.parseResult = [];
				
				lines.forEach(line => {
					const item = this.parseLine(line);
					if (item) {
						this.parseResult.push(item);
					}
				});
			},
			parseLine(line) {
				line = line.trim();
				if (!line) return null;
				
				// 尝试匹配"项目名 数量单位"格式
				let match = line.match(/^(.+)\s+(\d+)(.*)$/);
				if (match) {
					return {
						name: match[1].trim(),
						quantity: parseInt(match[2]),
						unit: this.extractUnit(match[3])
					};
				}
				
				// 尝试匹配"数量单位 项目名"格式
				match = line.match(/^(\d+)(.*)\s+(.+)$/);
				if (match) {
					return {
						name: match[3].trim(),
						quantity: parseInt(match[1]),
						unit: this.extractUnit(match[2])
					};
				}
				
				// 尝试匹配"项目名 x 数量"格式
				match = line.match(/^(.+)\s+x\s+(\d+)$/i);
				if (match) {
					return {
						name: match[1].trim(),
						quantity: parseInt(match[2]),
						unit: '个'
					};
				}
				
				// 仅项目名格式
				return {
					name: line,
					quantity: 1,
					unit: '个'
				};
			},
			extractUnit(text) {
				text = text.trim();
				for (const unit of this.units) {
					if (text.includes(unit)) {
						return unit;
					}
				}
				return '个';
			},
			confirmParse() {
				this.items = [...this.parseResult];
				this.showModal = false;
				this.parseResult = [];
				this.parseText = '';
				this.saveData();
			},
			cancelParse() {
				this.showModal = false;
				this.parseResult = [];
				this.parseText = '';
			},
			
			// 描述与分享功能
			copyDescription() {
				if (this.description.length === 0) return;
				
				const text = this.description.join('\n');
				uni.setClipboardData({
					data: text,
					success: () => {
						this.copyStatus = '已复制';
						setTimeout(() => {
							this.copyStatus = '复制描述';
						}, 2000);
						
						// 添加到历史记录
						this.addToHistory(text);
					}
				});
			},
			addToHistory(content) {
				const today = new Date().toLocaleDateString();
				
				// 检查是否已有今天的记录
				const existingIndex = this.history.findIndex(item => item.date === today);
				
				if (existingIndex !== -1) {
					// 更新今天的记录
					this.history[existingIndex].content = content;
				} else {
					// 添加新记录
					this.history.unshift({
						date: today,
						content: content
					});
					
					// 保留最近5条记录
					if (this.history.length > 5) {
						this.history = this.history.slice(0, 5);
					}
				}
				
				this.saveData();
			},
			
			// 历史记录功能
			copyHistory(index) {
				const content = this.history[index].content;
				uni.setClipboardData({
					data: content,
					success: () => {
						uni.showToast({
							title: '已复制历史记录',
							icon: 'none'
						});
					}
				});
			},
			parseHistory(index) {
				this.parseText = this.history[index].content;
				this.showModal = true;
				this.parseItems();
			},
			
			// 数据持久化
			saveData() {
				try {
					uni.setStorageSync('itemList', JSON.stringify(this.items));
					uni.setStorageSync('history', JSON.stringify(this.history));
				} catch (e) {
					console.error('保存数据失败：', e);
				}
			},
			loadData() {
				try {
					const itemsData = uni.getStorageSync('itemList');
					const historyData = uni.getStorageSync('history');
					
					if (itemsData) {
						this.items = JSON.parse(itemsData);
					}
					
					if (historyData) {
						this.history = JSON.parse(historyData);
					}
				} catch (e) {
					console.error('加载数据失败：', e);
				}
			}
		}
	}
</script>

<style>
	.container {
		padding: 20px;
		font-size: 16px;
	}
	
	/* 标题样式 */
	.header {
		text-align: center;
		margin-bottom: 20px;
	}
	
	.title {
		font-size: 24px;
		font-weight: bold;
		color: #333;
	}
	
	/* 添加区域样式 */
	.add-area {
		display: flex;
		margin-bottom: 15px;
	}
	
	.add-input {
		flex: 1;
		height: 45px;
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 0 10px;
		font-size: 16px;
		margin-right: 10px;
	}
	
	.add-btn {
		width: 80px;
		height: 45px;
		background-color: #5c9ce6;
		color: white;
		border: none;
		border-radius: 5px;
		font-size: 16px;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}
	
	/* 操作区域样式 */
	.action-area {
		display: flex;
		justify-content: space-between;
		margin-bottom: 15px;
	}
	
	.action-btn {
		width: 48%;
		height: 45px;
		border-radius: 5px;
		border: none;
		font-size: 16px;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}
	
	.parse-btn {
		background-color: #7ac29a;
		color: white;
	}
	
	.reset-btn {
		background-color: #e6a253;
		color: white;
	}
	
	/* 项目列表样式 */
	.items-list {
		margin-bottom: 15px;
	}
	
	.item-card {
		display: flex;
		align-items: center;
		padding: 15px;
		margin-bottom: 10px;
		background-color: #f8f8f8;
		border-radius: 5px;
		position: relative;
		box-shadow: 0 1px 3px rgba(0,0,0,0.05);
	}
	
	.item-card.dragging {
		opacity: 0.7;
		background-color: #e0e0e0;
	}
	
	.drag-handle {
		margin-right: 10px;
		color: #999;
		font-size: 20px;
	}
	
	.item-checkbox {
		transform: scale(1.2);
		margin-right: 10px;
	}
	
	.item-name {
		flex: 1;
		font-size: 18px;
	}
	
	.item-quantity {
		display: flex;
		align-items: center;
		margin-right: 10px;
	}
	
	.quantity-btn {
		width: 35px;
		height: 35px;
		background-color: #5c9ce6;
		color: white;
		border-radius: 4px;
		border: none;
		font-size: 18px;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 1px 2px rgba(0,0,0,0.1);
	}
	
	.quantity-text {
		width: 40px;
		text-align: center;
		font-size: 18px;
	}
	
	.delete-btn {
		width: 30px;
		height: 30px;
		background-color: #d57575;
		color: white;
		border-radius: 15px;
		border: none;
		font-size: 18px;
		line-height: 30px;
		text-align: center;
		padding: 0;
		box-shadow: 0 1px 2px rgba(0,0,0,0.1);
	}
	
	/* 添加新项目按钮样式 */
	.add-new-btn {
		width: 100%;
		height: 50px;
		background-color: #5c9ce6;
		color: white;
		border: none;
		border-radius: 5px;
		font-size: 18px;
		margin-bottom: 20px;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}
	
	/* 描述区域样式 */
	.description-area {
		background-color: #f8f8f8;
		padding: 15px;
		border-radius: 5px;
		margin-bottom: 20px;
		box-shadow: 0 1px 3px rgba(0,0,0,0.05);
	}
	
	.description-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
		display: block;
	}
	
	.description-content {
		margin-bottom: 15px;
	}
	
	.description-line {
		display: block;
		margin-bottom: 5px;
		font-size: 16px;
	}
	
	.copy-btn {
		width: 100%;
		height: 45px;
		background-color: #5c9ce6;
		color: white;
		border: none;
		border-radius: 5px;
		font-size: 16px;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}
	
	/* 历史记录区域样式 */
	.history-area {
		background-color: #f8f8f8;
		padding: 15px;
		border-radius: 5px;
		box-shadow: 0 1px 3px rgba(0,0,0,0.05);
	}
	
	.history-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
		display: block;
	}
	
	.history-item {
		background-color: white;
		padding: 10px;
		border-radius: 5px;
		margin-bottom: 10px;
		box-shadow: 0 1px 2px rgba(0,0,0,0.05);
	}
	
	.history-date {
		font-size: 14px;
		color: #666;
		margin-bottom: 5px;
		display: block;
	}
	
	.history-content {
		font-size: 16px;
		margin-bottom: 10px;
		display: block;
	}
	
	.history-actions {
		display: flex;
		justify-content: flex-end;
	}
	
	.history-btn {
		width: 80px;
		height: 35px;
		margin-left: 10px;
		background-color: #5c9ce6;
		color: white;
		border: none;
		border-radius: 5px;
		font-size: 14px;
		box-shadow: 0 1px 2px rgba(0,0,0,0.1);
	}
	
	/* 解析弹窗样式 */
	.modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1000;
	}
	
	.modal-content {
		width: 90%;
		max-height: 80%;
		background-color: white;
		border-radius: 10px;
		padding: 20px;
		overflow-y: auto;
		box-shadow: 0 4px 12px rgba(0,0,0,0.15);
	}
	
	.modal-title {
		font-size: 20px;
		font-weight: bold;
		margin-bottom: 10px;
		display: block;
		text-align: center;
	}
	
	.modal-desc {
		font-size: 14px;
		color: #666;
		margin-bottom: 15px;
		display: block;
	}
	
	.parse-input {
		width: 100%;
		height: 120px;
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 10px;
		font-size: 16px;
		margin-bottom: 15px;
	}
	
	.parse-result {
		margin-bottom: 15px;
	}
	
	.result-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 10px;
		display: block;
	}
	
	.result-item {
		padding: 8px;
		background-color: #f0f0f0;
		border-radius: 5px;
		margin-bottom: 5px;
	}
	
	.modal-buttons {
		display: flex;
		justify-content: space-between;
	}
	
	.modal-btn {
		height: 45px;
		border-radius: 5px;
		border: none;
		font-size: 16px;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}
	
	.cancel-btn {
		width: 30%;
		background-color: #f0f0f0;
		color: #333;
	}
	
	.parse-action-btn {
		width: 30%;
		background-color: #7ac29a;
		color: white;
	}
	
	.confirm-btn {
		width: 30%;
		background-color: #5c9ce6;
		color: white;
	}
</style>
